<template>
  <div class="page-wrapper">
    <c-card title="站点列表" class="com-wrapper">
      <el-button slot="func" type="primary" size="small" class="item" @click="showAddDlg">添加</el-button>
      <div class="search-row">
        <div>
          <div class="item">
            <label>公司</label>
            <el-select
              v-model="comId"
              size="small"
              placeholder="选择公司"
              clearable
              @change="_getStations"
            >
              <el-option v-for="c in comList1" :key="c.pkid" :label="c.name" :value="c.pkid"></el-option>
            </el-select>
          </div>
          <c-search
            v-model="searchText"
            :height="30"
            :width="200"
            placeholder="站点名称搜索"
            class="item"
            @submit="_getStations"
          />
        </div>
      </div>
      <el-table
        ref="table"
        v-loading="loading"
        :data="stations"
        stripe
        style="width: 100%"
        height="494"
      >
        <el-table-column prop="substationname" label="站点名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="voltagelevel" label="电压等级" width="100"></el-table-column>
        <el-table-column prop="substationtype" label="站点类型" width="150">
          <template v-slot="{row}">{{ types[row.substationtype - 1] }}</template>
        </el-table-column>
        <!-- <el-table-column prop="areaNo" label="区域" width="150">
          <template slot-scope="scope">
            <div v-bind="handleClick(scope.row.areaNo)">
              {{ scope.row.areaNo }}
            </div>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="areaNo" label="区域" :formatter="formatRole"></el-table-column> -->
        <el-table-column prop="address" label="详细地址" show-overflow-tooltip></el-table-column>
        <el-table-column prop="transformercount" label="变压器数量" width="100"></el-table-column>
        <el-table-column prop="loadcapacity" label="容量" width="100"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button size="small" type="text" @click="showEditDlg(row)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteCom(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getStations"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg
      v-if="stationInfo"
      :title="(stationInfo.substationid ? '编辑' : '添加') + '站点'"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="stationInfo"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
        style="width: 100%;"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="站点名称" prop="substationname">
              <el-input v-model="stationInfo.substationname" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="区域" prop="areaNo">
              <el-select v-model="stationInfo.areaNo" size="small">
                <el-option v-for="g in gvars" :key="g.areaNo" :label="g.name" :value="g.areaNo"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="配电站类型" prop="substationtype">
              <el-select v-model="stationInfo.substationtype" size="small">
                <el-option v-for="(t, i) in types" :key="i" :label="t" :value="i+1"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="变压器数量" prop="transformercount">
              <el-input v-model="stationInfo.transformercount" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="电压等级" prop="voltagelevel">
              <!-- <el-input v-model="stationInfo.voltagelevel" size="small"></el-input> -->
              <el-select v-model="stationInfo.voltagelevel">
                <el-option
                  v-for="item in options"
                  :key="item.pkid"
                  :label="item.label"
                  :value="item.pkid"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="容量" prop="loadcapacity">
              <el-input v-model="stationInfo.loadcapacity" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row last-row">
          <div class="row-item">
            <el-form-item label="坐标" prop="location">
              <el-input v-model="stationInfo.location" size="small" @click.native="loadMap">
                <i slot="suffix" class="el-input__icon el-icon-position"></i>
              </el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="地址" prop="address">
              <el-input v-model="stationInfo.address" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button size="small" type="danger" @click="submitForm">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </c-dlg>
    <c-dlg :visible.sync="mapVisible" :type="2" title="选择坐标" no-padding>
      <el-select
        v-model="address"
        :loading="loading1"
        :remote-method="searchPos"
        filterable
        remote
        size="small"
        class="pos-input"
        placeholder="输入地址"
        @change="getPoint"
      >
        <el-option v-for="(s, i) in sugestions" :key="i" :label="s" :value="s"></el-option>
      </el-select>
      <div id="map-container"></div>
    </c-dlg>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CSearch from "@/components/CSearch";
import CDlg from "@/components/CDlg";
import { editStation, deleteStation } from "@/api/user";
import { calcPageNum } from "@/utils";
let map = null,
  maker = null;
const BMap = window.BMap;
export default {
  name: 'Station',
  components: {
    CCard,
    CSearch,
    CDlg
  },
  data() {
    return {
      searchText: null,
      loading: false,
      loading1: false,
      stations: [],
      dialogVisible: false,
      stationInfo: null,
      gvars: null,
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      rules: {},
      mapVisible: false,
      address: "",
      sugestions: [],
      comId: null,
      types: [
        "专用变电站",
        "专用开闭所",
        "专用配电房",
        "箱变",
        "水电厂",
        "火电厂",
        "核电站",
        "变电站/配电房",
        "转发厂",
        "系统厂(华普)",
        "统计厂(大数据)",

      ],
      options: [],
      value: ''
    };
  },
  computed: {
    comList1() {
      return this.$store.getters.comList;
    }
  },
  mounted() {
    this._getGvars();
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);
    this._getStations();
    this.dropDown()
  },
  methods: {
    handleClick (row) {
      // console.log(row)
    },
    formatRole(row, column) {
      const gvarss = localStorage.getItem('gvars')
      console.log('gvars', JSON.parse(gvarss))
      if (row.areaNo && gvarss.length !== 0 && gvarss !== []) {
        // gvars.filter(item => {
        //   return item.areaNo === row.areaNo
        // })
        // console.log(address[0].name)
        // return address[0].name;
        // gvars.filter(function(item) {
        //   return item.areaNo === row.areaNo
        // })
        // gvarss.filter(item => item.areaNo === row.areaNo)
        // return '111'
        // gvarss.map(item => {
        //   if (item.areaNo === row.areaNo) {
        //     console.log(item.areaNo[0])
        //   }
        // })
        return '11'
      } else {
        return null;
      }
    },
    _getStations() {
      console.log(this.comId)
      const substationname = this.searchText;
      const params = {
        pageNo: this.page.index,
        pageSize: this.page.size,
        clientId: this.comId,
        substationname: substationname || null
      };
      this.loading = true;
      return this.$axios
        .get("plat/sys/substation/list", { params })
        .then(res => {
          if (res.code === 1) {
            this.$set(this.page, "total", res.data.total);
            const stations = res.data.rows

            this.stations = stations.map(item => {
              // const govID = this.gvars.filter(res => {
              //   return res.areaNo === item.govID
              // })
              const Josn = {
                createTime: item.createTime,
                updateTime: item.updateTime,
                status: item.status,
                substationid: item.substationid,
                // areaNo: govID[0].name,
                areaNo: item.govID,
                clientID: item.clientID,
                responsibleID: item.responsibleID,
                substationname: item.substationname,
                voltagelevel: item.voltagelevel,
                substationtype: item.substationtype,
                starttime: item.starttime,
                svgNames: item.svgNames,
                address: item.details,
                location: item.location,
                jointime: item.jointime,
                expirationtime: item.expirationtime,
                transformercount: item.transformercount,
                loadcapacity: item.loadcapacity,
                sort: item.sort,
                operUserID: item.operUserID,
                volLevelLabel: item.volLevelLabel
              }
              return Josn
            })
          } else throw res.msg;
        })
        .catch(e => this.$message.error(e))
        .finally(() => (this.loading = false));
    },
    _getGvars() {
      return this.$axios
        .get("plat/sys/common/govareat/dropDownList")
        .then(res => {
          if (res.code === 1) {
            this.gvars = res.data;
            localStorage.setItem('gvars', JSON.stringify(res.data))
          }
        })
        .catch(e => {});
    },
    showAddDlg() {
      if (!this.stationInfo || (this.stationInfo && this.stationInfo.substationid)) {
        this.stationInfo = {};
      }
      this.dialogVisible = true;
    },
    showEditDlg(row) {
      if (
        this.stationInfo &&
        this.stationInfo.substationid === row.substationid
      ) {
        this.dialogVisible = true;
      } else {
        this.stationInfo = row;
        this.dialogVisible = true;
      }
      console.log('编辑数据', this.stationInfo)
    },
    deleteCom(row) {
      this.$confirm("此操作将永久删除该公司, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return deleteStation(row.substationid)
          .then(() => {
            this._getStations();
            // this.$store.dispatch("user/getComList");
            this.$message.success("刪除成功");
          })
          .catch(e => this.$message.error(e));
      });
    },
    loadMap() {
      this.mapVisible = true;
      this.$nextTick(async () => {
        const that = this;
        const p = [106.504108, 29.598395];
        map = new BMap.Map("map-container");
        const point = new BMap.Point(p[0], p[1]);
        map.centerAndZoom(point, 14);
        map.setCurrentCity("重庆");
        map.enableScrollWheelZoom(true);
        map.addEventListener("click", that.pointSelect);
        const geolocation = new BMap.Geolocation();
        if (this.stationInfo.location) {
          const pa = this.stationInfo.location.split(",");
          const mp = new BMap.Point(pa[0], pa[1]);
          maker = new BMap.Marker(mp);
          map.addOverlay(maker);
          map.panTo(mp);
          this.showInfoWnd(mp);
        } else {
          geolocation.getCurrentPosition(
            function(r) {
              if (this.getStatus() === window.BMAP_STATUS_SUCCESS) {
                maker = new BMap.Marker(r.point);
                map.addOverlay(maker);
                map.panTo(r.point);
                that.showInfoWnd(r.point);
              } else {
                that.$message.error("定位失败, 请手动选择位置!");
              }
            },
            { enableHighAccuracy: true }
          );
        }
      });
    },
    pointSelect(e) {
      const point = e.point;
      maker = new BMap.Marker(point);
      map.clearOverlays();
      map.addOverlay(maker);
      map.panTo(point);
      this.$nextTick(() => {
        this.showInfoWnd(point);
      });
    },
    showInfoWnd(point) {
      var myGeo = new BMap.Geocoder();
      // 根据坐标得到地址描述
      this.$set(this.stationInfo, "location", point.lng + "," + point.lat);
      myGeo.getLocation(point, result => {
        if (result) {
          let title, address;
          const p = result.surroundingPois[0];
          if (!p) {
            title = " ";
            address = result.address;
          } else {
            title = p.title;
            address = p.address;
          }
          var opts = {
            width: 200, // 信息窗口宽度
            height: 100, // 信息窗口高度
            title: title // 信息窗口标题
          };
          var infoWindow = new BMap.InfoWindow("地址：" + address, opts);
          map.openInfoWindow(infoWindow, point);
          this.$set(this.stationInfo, "address", address);
        }
      });
    },
    searchPos(v) {
      const that = this;
      const options = {
        onSearchComplete: function(results) {
          if (local.getStatus() === window.BMAP_STATUS_SUCCESS) {
            // 判断状态是否正确
            var s = [];
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              s.push(
                results.getPoi(i).title + " - " + results.getPoi(i).address
              );
            }
            that.sugestions = s;
          }
        }
      };
      var local = new BMap.LocalSearch(map, options);
      local.search(v);
    },
    getPoint(address) {
      var myGeo = new BMap.Geocoder();
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(
        address,
        point => {
          if (point) {
            map.clearOverlays();
            map.addOverlay(new BMap.Marker(point));
            map.panTo(point);
            this.showInfoWnd(point);
          }
        },
        "重庆市"
      );
    },
    submitForm() {
      if (this.stationInfo.clientID === undefined) {
        const load = this.$loading();
        const stationInfo = {
          substationId: this.stationInfo.substationId,
          areaNo: this.stationInfo.areaNo,
          clientID: this.comId,
          responsibleID: this.stationInfo.responsibleID,
          substationname: this.stationInfo.substationname,
          voltagelevel: this.stationInfo.voltagelevel,
          substationtype: this.stationInfo.substationtype,
          svgNames: this.stationInfo.svgNames,
          address: this.stationInfo.address,
          location: this.stationInfo.location,
          transformercount: this.stationInfo.transformercount,
          loadcapacity: this.stationInfo.loadcapacity
        }
        return editStation(stationInfo)
          .then(() => {
            this.dialogVisible = false;
            this.stationInfo = null;
            this._getStations();
          // this.$store.dispatch("user/getComList");
          })
          .catch(e => this.$message.error(e))
          .finally(() => load.close());
      } else {
        const load = this.$loading();
        return editStation(this.stationInfo)
          .then(() => {
            this.dialogVisible = false;
            this.stationInfo = null;
            this._getStations();
          // this.$store.dispatch("user/getComList");
          })
          .catch(e => this.$message.error(e))
          .finally(() => load.close());
      }
    },
    dropDown() {
      this.loading = true;
      return this.$axios
        .get("plat/sys/volLevel/dropDown")
        .then(res => {
          if (res.code === 1) {
            this.options = res.data;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => (this.loading = false));
    },
  },
};
</script>

<style lang="scss" scoped>
#map-container {
  height: 500px;
  width: 1000px;
}
.pos-input {
  position: absolute;
  top: 10px;
  left: 20px;
  width: 300px;
  z-index: 99;
}
</style>
